var time = require("../../util");
Page({
  data: {
    list: {},
    tabName: ['未印', '已印'],
    TabCur: 0,
    type: "进行中",
    notice: ""
  },
  onLoad: function (options) {
    this.refreshList()
  }, refreshList() {
    var that = this
    wx.cloud.callFunction({ name: 'function', data: { type: "getAllTask" } }).then(res => {
      var tmpData = []
      res.result.data.forEach(element => {
        if (element.type == that.data.type) {
          var tmpEle = element
          tmpEle.upTime = time.formatTimeTwo(tmpEle.upTime, "Y年M月D日h:m")
          tmpData.push(tmpEle)
        }
      });
      that.setData({ list: tmpData })
    })
  }, select(e) {
    this.setData({ TabCur: e.currentTarget.dataset.id, scrollLeft: (e.currentTarget.dataset.id - 1) * 60 })
    if (e.currentTarget.dataset.id == 0) {
      this.setData({ type: "进行中" })
      this.refreshList()
    } else {
      this.setData({ type: "已完成" })
      this.refreshList()
    }
  }, listTap(a) {
    var that = this
    var itemData = this.data.list[a.currentTarget.dataset.id]
    if (itemData.type == "进行中") {
      wx.showModal({
        title: '提示',
        content: '确定标为已完成?',
        success: function (sm) {
          if (sm.confirm) {
            wx.cloud.callFunction({ name: 'function', data: { type: "setFinish", id: itemData._id } }).then(res => { that.refreshList() })
          }
        }
      })
    }
  }, watchNotice(a) {
    this.setData({ notice: a.detail.value })
  }, updateNotice() {
    wx.cloud.callFunction({ name: 'function', data: { type: "updateNotice", notice: this.data.notice } }).then(res => {
      wx.showToast({ title: '已更新公告', icon: 'success', duration: 1000 })
    })
  }, share(a) {
    var that = this
    var itemData = this.data.list[a.currentTarget.dataset.id]
    console.log(itemData)
    wx.cloud.downloadFile({
      fileID: itemData.fileId,
      success: sres => {
        wx.getFileSystemManager().saveFile({
          tempFilePath: sres.tempFilePath,
          filePath: wx.env.USER_DATA_PATH + "/" + itemData.fileName, 
          success(tres) {
            wx.showToast({title: '请稍等'})
            wx.openDocument({
              filePath: tres.savedFilePath,
              showMenu: true,
              fail: fres => {
                wx.showToast({title: fres})
              },
            })
          },
          fail(tres) {
            wx.showToast({title: fres})
          }
        })
      },
      fail: err => {
        console.log("下载附件失败", err)
      }
    })
  },onShareAppMessage(){

  },onShareTimeline(){
    
  }
})